class myPromise{
  constructor() {
    this.state = 'pending';
    this.value = 'undefined';
    this.reason = 'undefined';
    this.success = [];
    this.fail = [];

    let resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled'
        this.value = value;
        this.success.forEach(fn => fn());
      }
    }

    let reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected'
        this.reason = reason;
        this.fail.forEach(fn => fn());
      }
    }

    try {
      // 执行
      executor(resolve, reject)
    } catch (error) {
      // 若出错，直接调用reject
      reject(error)
    }
  }

  then(onFulfilled, onRejected) {
    if (this.state === 'fulfilled') {
      onFulfilled(this.value);
    }
    if (this.state === 'rejected') {
      onRejected(this.reason);
    }
    if (this.state === 'pending') {
      this.success.push(() => { onFulfilled(this.value) });
      this.reason.push(() => { onRejected(this.reason) });
    }
  }
}

Promise.race = (promises) => {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then(v => {
          resolve(v);
      }, e => {
        reject(e);
      })
    }
  })
}

let res = Promise.race([new Promise((resolve,reject) => {
  setTimeout(() => {
    resolve(111)
  }, 0)
}),new Promise((resolve,reject) => {
  resolve(222)
}),new Promise((resolve,reject) => {
  resolve(333)
})])

res.then(v=> console.log(v),r => console.log(r))
